package cn.topevery.garden.wapi.config;


import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class DruidConfig {

    @Value("${spring.datasource.druid.loginUsername:admin}")
    private String loginUsername;

    @Value("${spring.datasource.druid.loginPassword:123}")
    private  String loginPassword;

//    @ConfigurationProperties(prefix = "spring.datasource")
//    @Bean
//    public DataSource druidDataSource(){
//        //return  new DruidDataSource();
//        //DruidDataSource dataSource = DataSourceFactory.getDataSource(Database.gardenDbExecute.getConnectionSetting());
//
//        //return  dataSource;
//        return DataSourceFactory.getDataSource(Database.gardenDbExecute.getConnectionSetting());
//    }

    //后台监控：web.xml, ServletRegistrationBean
    // 因为springBoot内置了servlet容器，所以没有web.xml，替代方法：ServletRegistionBean
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(),"/druid/*");

        //配置用于登录DRUID后台的账号和密码
        HashMap<String, String> initParameters =  new HashMap<>();
        //注意：loginUsername和loginPassword这两个key是固定的，不能改名
        initParameters.put("loginUsername",loginUsername);
        initParameters.put("loginPassword",loginPassword);

        //allow表示ip白名单，""表示ip可访问，如果写localhost表示本地可访问
        initParameters.put("allow","");

        //deny表示ip黑名单,优先级高于allow
        //initParameters.put("deny","192.168.1.123");

        //设置初始化参数
        bean.setInitParameters(initParameters);

        return bean;
    }

    //filter
    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean bean = new FilterRegistrationBean();

        bean.setFilter(new WebStatFilter());

        //设置过滤的内容
        Map<String, String> initParameters =new HashMap<>();

        //排除统计以下内容
        initParameters.put("exclusions","*.js,*.css,/druid/*");
        bean.setInitParameters(initParameters);

        return bean;
    }
}
